export const getImgPath = {
  methods: {
    // 传递过来的图片地址需要处理后才能正常使用
    getImgPath(path) {
      let suffix;
      if (!path) {
        return 'http://test.fe.ptdev.cn/elm/elmlogo.jpeg'
      }
      if (path.indexOf('jpeg') !== -1) {
        suffix = '.jpeg'
      } else {
        suffix = '.png'
      }
      let url = '/' + path.substr(0, 1) + '/' + path.substr(1, 2) + '/' + path.substr(3) + suffix;
      return 'https://fuss10.elemecdn.com' + url
    }
  }
}
// base64 to blod
export const dataURLtoBlob = {
  methods: {
    dataURLtoBlob(dataurl) {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {type: mime})
    }
  }
}

/**
 * [工具] 服务器端授权单文件上传 oss
 * @param base64File 上传的文件base64 格式
 * @param dir 目录地址
 * @param BucketName 地址
 * @依赖 npm install es6-uuid --save
 * @依赖 storeConst.js 中添加 OSSSIGN: 'OSS_SIGN' // oss 签名 key
 * @依赖 this.dataURLtoBlob方法
 * @依赖 环境变量 BUKETNAME: '"hd-huludao"', // oss 存储空间
 * @依赖 环境变量 BUKETDIR: '"upload"' // oss 默认存储目录
 * @使用示例 由于获取图片地址是异步操作,想要做到同步,调用方式有些不同
 * // 1.创建获取图片地址,注意函数类型是async, 内部需要循环,函数也要是async,循环体内部才能使用await
  async getOssPath() {
    let osspath = [];
    // 注意,千万不能使用 foreach
    for (let element of this.goodsDetial) {
      if (element.type === 'image') {
        // 将 base64 转换为文件
        osspath.push(await this.upLoadFileByBase64(element.value))
      }
    }
    return osspath
  }
  // 2. 调用方法需要是async类型,这样在内部才能使用 await 等待异步完成继续执行
  // 保存产品
  async saveProd() {
    let osspath = await this.getOssPath()
    console.log('==oss==================================');
    console.log(osspath);
    console.log('=====oss===============================');
  }
 */
import UUID from 'es6-uuid'
export const upLoadFileByBase64 = {
  methods: {
    upLoadFileByBase64(base64File, dir = process.env.BUKETDIR, bucketName = process.env.BUKETNAME) {
      return new Promise((resolve, reject) => {
        // store key
        let key = this.STORECONST.OSSSIGN + bucketName + dir
        let file = null
        if (base64File) {
          file = this.dataURLtoBlob(base64File)
        }
        let osssgin = this.store.get(key)
        // 判断授权时间是否过期
        if (!osssgin) {
          this.ossSign(dir, bucketName, key, (dir, policy, accessid, signature, host) => {
            resolve(this.upLoadFileSet(dir, policy, accessid, signature, host, file))
          })
        } else {
          // 授权时间未过期,获取签名内容
          let dir = osssgin.dir
          let policy = osssgin.policy
          let accessid = osssgin.accessid
          let signature = osssgin.signature
          let host = osssgin.host
          resolve(this.upLoadFileSet(dir, policy, accessid, signature, host, file))
        }
      })
    },
    // 获得签名回调
    ossSign(dir, bucketName, key, callback) {
      // 请求授权
      this.hdAjax({
        url: this.API.wl.getOssSing,
        data: {
          bucketName: bucketName,
          dir: dir
        },
        success: (resultData) => {
          // 授权成功
          if (resultData.status === 1 && resultData.result) {
            // 设置签名有效期 key 构成 前缀+buketname+目录
            this.store.set(key, resultData.result, resultData.result.expire * 1000)
            let dir = resultData.result.dir
            let policy = resultData.result.policy
            let accessid = resultData.result.accessid
            let signature = resultData.result.signature
            let host = resultData.result.host
            return callback(dir, policy, accessid, signature, host)
          }
        },
        fail: (resErr) => {
          this.dialog.toast({mes: resErr.errmsg})
        }
      })
    },
    // 上传文件
    upLoadFileSet(dir, policy, accessid, signature, host, file) {
      return new Promise((resolve, reject) => {
        let formData = new FormData()
        // 生成文件名称 时间戳
        let filename = UUID(32, 36)
        // 获取文件类型
        let fileType = file.type
        let suffix = ''
        let index = fileType.lastIndexOf('/')
        suffix = fileType.substring((index + 1), fileType.length)
        // 文件目录+ 文件名
        formData.append('key', dir + filename + '.' + suffix)
        formData.append('policy', policy)
        formData.append('OSSAccessKeyId', accessid)
        formData.append('success_action_status', 200)
        formData.append('callback', '');
        formData.append('signature', signature)
        formData.append('file', file)
        this.hdAjax({
          url: host,
          method: 'post',
          data: formData,
          success: (resultData) => {
            if (resultData.errcode === 0) {
              // 上传成功后返回上传地址
              resolve(`${host}${dir}${filename}.${suffix}`)
            }
          },
          fail: (resErr) => {
            this.dialog.toast({mes: resErr.errmsg})
          }
        })
      })
    }
  }
}
